<template>
  <div class="city">
    <city-header @changeCity="changCity"></city-header>
    <city-list :cityList="cityList" :hotCity="hotCity" :searchList="searchList"></city-list>
  </div>
</template>

<script>
import cityHeader from "./header.vue"
import cityList from "./cityList.vue"
export default {
  components:{
    cityHeader,
    cityList
  },
  data(){
    return{
      //热门城市
       hotCity:[],
      //城市列表
      cityList:"",//完整的城市列表
      inputValue:"",//搜索城市输入的值
      searchList:[], //搜索城市渲染的列表
      allCity:[], //所有城市的集合
    }
  },
  methods:{
    //获取城市的数据
    getCity(){
      this.$http.get("http://www.qunar/citylist.com").then((res)=>{
        if(res.status == 200){
          this.hotCity = res.data.data.hotCities
          //当输入框没有输入内容的时候渲染完整的城市列表
          if(this.inputValue == ""){
            this.cityList = res.data.data.cities
          }
          //当输入框有内容的时候渲染输入相关内容的城市列表
          else{
            this.cityList = ""
            this.searchList= []
            this.allCity = []
            for(let key in res.data.data.cities){
              let item = res.data.data.cities[key]
               item.forEach(option=>{
                this.allCity.push(option)
              })
            }
            this.allCity.forEach(item=>{
             if(item.spell.startsWith(this.inputValue)||item.name.indexOf(this.inputValue)!=-1){
               this.searchList.push(item)
              }
           })
          }
        }
      })
    },
    changCity(val){
      this.inputValue = val
      this.getCity()
    }
  },
  created(){
    this.getCity()
  }
}
</script>

<style lang="less">
body,h4,ul{
  margin: 0;
  padding: 0;
}
ul{
  list-style: none;
}
h4{
  font-weight: normal;
}
</style>